<?php
/**
 * 分销功能API接口
 */

namespace app\controller\api;

use app\FrontendController;
use app\model\DistributionModel;
use app\model\DistributionCommissionModel;
use app\model\DistributionWithdrawalModel;
use app\model\CustomerModel;
use think\facade\Db;

class Distribution extends FrontendController
{
    /**
     * 分销设置
     */
    public function settings()
    {
        $settings = DistributionModel::getSettings();
        return json(['status' => 0, 'settings' => $settings]);
    }
    
    /**
     * 申请成为分销员
     */
    public function apply()
    {
        global $_W;
        
        if (empty($_W['customer'])) {
            return json(['status' => 1, 'message' => '请先登录']);
        }
        
        $customer_id = $_W['customer']['id'];
        
        // 检查是否已经是分销员
        $distributor = DistributionModel::where(['customer_id' => $customer_id])->find();
        if ($distributor) {
            return json(['status' => 1, 'message' => '您已经是分销员了']);
        }
        
        // 获取分销设置
        $settings = DistributionModel::getSettings();
        
        // 检查分销功能是否开启
        if (empty($settings['enabled'])) {
            return json(['status' => 1, 'message' => '分销功能未开启']);
        }
        
        // 根据分销模式检查是否可以申请
        switch ($settings['mode']) {
            case 'everyone':
                // 人人分销，直接通过
                break;
            case 'specified':
                // 指定分销，需要后台审核
                return json(['status' => 1, 'message' => '指定分销模式下需要后台审核']);
            case 'threshold':
                // 满额分销，检查消费金额
                $total_amount = 0; // TODO: 获取用户总消费金额
                if ($total_amount < $settings['threshold_amount']) {
                    return json(['status' => 1, 'message' => '消费金额未达到申请条件']);
                }
                break;
        }
        
        // 添加分销员
        $data = [
            'customer_id' => $customer_id,
            'level' => 1,
            'status' => $settings['mode'] === 'specified' ? 0 : 1, // 指定分销需要审核
            'create_time' => date('Y-m-d H:i:s')
        ];
        
        $result = DistributionModel::addDistributor($data);
        if ($result) {
            return json(['status' => 0, 'message' => '申请成功']);
        } else {
            return json(['status' => 1, 'message' => '申请失败']);
        }
    }
    
    /**
     * 获取分销员信息
     */
    public function info()
    {
        global $_W;
        
        if (empty($_W['customer'])) {
            return json(['status' => 1, 'message' => '请先登录']);
        }
        
        $customer_id = $_W['customer']['id'];
        
        $distributor = DistributionModel::alias('d')
            ->join('customer c', 'd.customer_id = c.id')
            ->field('d.*, c.name as customer_name, c.telephone, c.avatar')
            ->where('d.customer_id', $customer_id)
            ->find();
            
        if (!$distributor) {
            return json(['status' => 1, 'message' => '您还不是分销员']);
        }
        
        return json(['status' => 0, 'data' => $distributor]);
    }
    
    /**
     * 获取分销佣金记录
     */
    public function commission_list()
    {
        global $_W;
        
        if (empty($_W['customer'])) {
            return json(['status' => 1, 'message' => '请先登录']);
        }
        
        $customer_id = $_W['customer']['id'];
        
        // 检查是否是分销员
        $distributor = DistributionModel::where(['customer_id' => $customer_id])->find();
        if (!$distributor) {
            return json(['status' => 1, 'message' => '您还不是分销员']);
        }
        
        $filter = [
            'customer_id' => $customer_id
        ];
        
        $page = $_GET['page'] ?? 1;
        $limit = $_GET['limit'] ?? 15;
        
        $result = DistributionCommissionModel::getCommissionRecords($filter, $page, $limit);
        return json(['status' => 0, 'data' => $result]);
    }
    
    /**
     * 申请提现
     */
    public function withdraw()
    {
        global $_W;
        
        if (empty($_W['customer'])) {
            return json(['status' => 1, 'message' => '请先登录']);
        }
        
        $customer_id = $_W['customer']['id'];
        
        // 检查是否是分销员
        $distributor = DistributionModel::where(['customer_id' => $customer_id])->find();
        if (!$distributor) {
            return json(['status' => 1, 'message' => '您还不是分销员']);
        }
        
        $amount = $_POST['amount'] ?? 0;
        $method = $_POST['method'] ?? '';
        $account_info = $_POST['account_info'] ?? '';
        
        if ($amount <= 0) {
            return json(['status' => 1, 'message' => '提现金额必须大于0']);
        }
        
        if ($amount > $distributor['withdrawable_commission']) {
            return json(['status' => 1, 'message' => '提现金额不能大于可提现佣金']);
        }
        
        // 获取分销设置
        $settings = DistributionModel::getSettings();
        
        // 检查最低提现金额
        if ($amount < $settings['min_withdrawal']) {
            return json(['status' => 1, 'message' => '提现金额不能低于最低提现金额']);
        }
        
        // 计算手续费
        $fee = $amount * ($settings['withdrawal_fee'] / 100);
        $actual_amount = $amount - $fee;
        
        // 创建提现申请记录
        $withdrawal_data = [
            'customer_id' => $customer_id,
            'amount' => $amount,
            'fee' => $fee,
            'actual_amount' => $actual_amount,
            'method' => $method,
            'account_info' => $account_info,
            'status' => 0, // 待审核
            'create_time' => date('Y-m-d H:i:s')
        ];
        
        $result = DistributionWithdrawalModel::addWithdrawalRecord($withdrawal_data);
        
        if ($result) {
            // 更新分销员的可提现佣金
            DistributionModel::where(['customer_id' => $customer_id])->update([
                'withdrawable_commission' => Db::raw('withdrawable_commission - ' . $amount)
            ]);
            
            return json(['status' => 0, 'message' => '申请成功']);
        } else {
            return json(['status' => 1, 'message' => '申请失败']);
        }
    }
    
    /**
     * 获取推广二维码
     */
    public function qrcode()
    {
        global $_W;
        
        if (empty($_W['customer'])) {
            return json(['status' => 1, 'message' => '请先登录']);
        }
        
        $customer_id = $_W['customer']['id'];
        
        // 检查是否是分销员
        $distributor = DistributionModel::where(['customer_id' => $customer_id])->find();
        if (!$distributor) {
            return json(['status' => 1, 'message' => '您还不是分销员']);
        }
        
        // TODO: 生成推广二维码
        
        return json(['status' => 0, 'qrcode_url' => '']);
    }
    
    /**
     * 获取推广数据统计
     */
    public function statistics()
    {
        global $_W;
        
        if (empty($_W['customer'])) {
            return json(['status' => 1, 'message' => '请先登录']);
        }
        
        $customer_id = $_W['customer']['id'];
        
        // 检查是否是分销员
        $distributor = DistributionModel::where(['customer_id' => $customer_id])->find();
        if (!$distributor) {
            return json(['status' => 1, 'message' => '您还不是分销员']);
        }
        
        // TODO: 获取推广数据统计
        
        $data = [
            'total_commission' => $distributor['total_commission'],
            'withdrawable_commission' => $distributor['withdrawable_commission'],
            'frozen_commission' => $distributor['frozen_commission'],
            'team_count' => 0, // TODO: 团队人数
            'order_count' => 0, // TODO: 推广订单数
        ];
        
        return json(['status' => 0, 'data' => $data]);
    }
    
    /**
     * 团队成员列表
     */
    public function team_list()
    {
        global $_W;
        
        if (empty($_W['customer'])) {
            return json(['status' => 1, 'message' => '请先登录']);
        }
        
        $customer_id = $_W['customer']['id'];
        
        // 检查是否是分销员
        $distributor = DistributionModel::where(['customer_id' => $customer_id])->find();
        if (!$distributor) {
            return json(['status' => 1, 'message' => '您还不是分销员']);
        }
        
        // TODO: 实现团队成员列表逻辑
        
        return json(['status' => 0, 'data' => ['list' => [], 'total' => 0]]);
    }
    
    /**
     * 团队统计
     */
    public function team_stats()
    {
        global $_W;
        
        if (empty($_W['customer'])) {
            return json(['status' => 1, 'message' => '请先登录']);
        }
        
        $customer_id = $_W['customer']['id'];
        
        // 检查是否是分销员
        $distributor = DistributionModel::where(['customer_id' => $customer_id])->find();
        if (!$distributor) {
            return json(['status' => 1, 'message' => '您还不是分销员']);
        }
        
        // TODO: 实现团队统计逻辑
        
        $data = [
            'level1_count' => 0,
            'level2_count' => 0,
            'total_count' => 0
        ];
        
        return json(['status' => 0, 'data' => $data]);
    }
    
    /**
     * 分销统计
     */
    public function statistics()
    {
        global $_W;
        
        if (empty($_W['customer'])) {
            return json(['status' => 1, 'message' => '请先登录']);
        }
        
        $customer_id = $_W['customer']['id'];
        
        // 检查是否是分销员
        $distributor = DistributionModel::where(['customer_id' => $customer_id])->find();
        if (!$distributor) {
            return json(['status' => 1, 'message' => '您还不是分销员']);
        }
        
        // TODO: 实现分销统计逻辑
        
        $data = [
            'total_commission' => $distributor['total_commission'],
            'withdrawable_commission' => $distributor['withdrawable_commission'],
            'frozen_commission' => $distributor['frozen_commission'],
            'team_count' => 0, // TODO: 团队人数
            'order_count' => 0 // TODO: 推广订单数
        ];
        
        return json(['status' => 0, 'data' => $data]);
    }
    
    /**
     * 佣金排行榜
     */
    public function commission_ranking()
    {
        // TODO: 实现佣金排行榜逻辑
        
        return json(['status' => 0, 'data' => []]);
    }
    
    /**
     * 订单排行榜
     */
    public function order_ranking()
    {
        // TODO: 实现订单排行榜逻辑
        
        return json(['status' => 0, 'data' => []]);
    }
    
    /**
     * 分销订单列表
     */
    public function order_list()
    {
        global $_W;
        
        if (empty($_W['customer'])) {
            return json(['status' => 1, 'message' => '请先登录']);
        }
        
        $customer_id = $_W['customer']['id'];
        
        // 检查是否是分销员
        $distributor = DistributionModel::where(['customer_id' => $customer_id])->find();
        if (!$distributor) {
            return json(['status' => 1, 'message' => '您还不是分销员']);
        }
        
        // TODO: 实现分销订单列表逻辑
        
        return json(['status' => 0, 'data' => ['list' => [], 'total' => 0]]);
    }
}